package com.nic.view.util.contactList;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.RelativeLayout;

import com.nic.view.R;
import com.nic.view.widget.CircleTextView;
import com.nic.view.widget.FullyLinearLayoutManager;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ContactRecycleView extends RelativeLayout {
    private SideBar sideBar;
    private RecyclerView listView;
    private CircleTextView circleTextView;
    private onSideBarSelectionListener barSelectionListener;
    private FullyLinearLayoutManager layoutManager;

    public SideBar getSideBar() {
        return sideBar;
    }

    public RecyclerView getListView() {
        return listView;
    }

    public CircleTextView getCircleTextView() {
        return circleTextView;
    }

    public ContactRecycleView(Context context) {
        super(context);
        init(context);
    }

    public ContactRecycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ContactRecycleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public ContactRecycleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        sideBar = new SideBar(context);
        sideBar.setBackground(new ColorDrawable(Color.parseColor("#00ffffff")));
        sideBar.setTextColor(ContextCompat.getColor(context, android.R.color.black));
        sideBar.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 8);
        int sideBarWidth = getResources().getDimensionPixelSize(R.dimen.dimen_16);
        RelativeLayout.LayoutParams paramBar = new RelativeLayout.LayoutParams(sideBarWidth, LayoutParams.MATCH_PARENT);
        paramBar.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        sideBar.setLayoutParams(paramBar);

        RelativeLayout.LayoutParams paramList = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//        paramList.addRule(RelativeLayout.RIGHT_OF, sideBar.getId());
//        paramList.rightMargin = sideBarWidth;
        listView = new RecyclerView(context);
        listView.setLayoutParams(paramList);
        listView.setVerticalScrollBarEnabled(false);
//        listView.setFastScrollEnabled(false);
//        listView.setDivider(new ColorDrawable(Color.parseColor("#EEEEEE")));
//        listView.setDividerHeight(getResources().getDimensionPixelOffset(R.dimen.dimen_0_5));
//        listView.setDividerHeight(0);
        listView.setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
        layoutManager = new FullyLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        listView.setLayoutManager(layoutManager);
        addView(listView);
        addView(sideBar);
        RelativeLayout.LayoutParams paramText = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        paramText.addRule(RelativeLayout.CENTER_IN_PARENT);
        circleTextView = new CircleTextView(context);
        circleTextView.setLayoutParams(paramText);
        addView(circleTextView);
        circleTextView.setVisibility(GONE);

        sideBar.setOnStrSelectCallBack(new SideBar.ISideBarSelectCallBack() {
            @Override
            public void onSelectDown(int index, String selectStr) {
                sideBar.setBackgroundResource(R.drawable.side_bar_bg);
                sideBar.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white));
                circleTextView.setVisibility(VISIBLE);
                circleTextView.setText(selectStr);
            }

            @Override
            public void onSelectUp() {
                sideBar.setBackgroundResource(android.R.color.transparent);
                sideBar.setTextColor(ContextCompat.getColor(getContext(), android.R.color.black));
                circleTextView.setVisibility(GONE);
                String text = circleTextView.getText().toString();
                if (barSelectionListener != null && !TextUtils.isEmpty(text)) {
                    barSelectionListener.onSelected(text);
                }
            }
        });
    }

    public void moveToPosition(int n) {
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            listView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = listView.getChildAt(n - firstItem).getTop();
            listView.scrollBy(0, top);
        } else {
            listView.scrollToPosition(n);
        }

    }

    public int findLastVisibleItemPosition() {
        return layoutManager.findLastVisibleItemPosition();
    }

    public int findFirstVisibleItemPosition() {
        return layoutManager.findFirstVisibleItemPosition();
    }


    /**
     * 是否隐藏字母列表
     *
     * @param visibility
     */
    public void setSideBarVisibility(int visibility) {
        sideBar.setVisibility(visibility);
        RelativeLayout.LayoutParams paramList = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        paramList.rightMargin = 0;
        listView.setLayoutParams(paramList);
    }

    public void setBarSelectionListener(onSideBarSelectionListener barSelectionListener) {
        this.barSelectionListener = barSelectionListener;
    }

    public interface onSideBarSelectionListener {
        void onSelected(String selectStr);
    }


    /**
     * 按照字母排序
     *
     * @param list
     * @param <T>
     */
    public static <T extends PinYinSortBean> void sort(List<T> list) {
        if (list != null && !list.isEmpty()) {
            Collections.sort(list, comparator);
        }

    }

    private static Comparator<PinYinSortBean> comparator = new Comparator<PinYinSortBean>() {
        @Override
        public int compare(PinYinSortBean o1, PinYinSortBean o2) {
            if (o1.getFirstLetter().equals("#") && !o2.getFirstLetter().equals("#")) {
                return 1;
            } else if (!o1.getFirstLetter().equals("#") && o2.getFirstLetter().equals("#")) {
                return -1;
            } else {
                return o1.getPinyin().compareToIgnoreCase(o2.getPinyin());
            }
//            if (o1.getPinyin().equals(o1.sortName()) && !o2.getPinyin().equals(o2.sortName())) {
//                return 1;
//            } else if (!o1.getPinyin().equals(o1.sortName()) && o2.getPinyin().equals(o2.sortName())) {
//                return -1;
//            } else {
//                return o1.getPinyin().compareToIgnoreCase(o2.getPinyin());
//            }
        }
    };

    /**
     * 插入标题
     *
     * @param list
     * @param factory
     * @param <T>
     */
    public static <T extends PinYinSortBean> void insertTitle(List<T> list, PinyinFactory factory) {
        sort(list);//字母排序

        String title = "";
        for (int i = 0; i < list.size(); i++) {
            T t = list.get(i);
//            System.out.println("->"+title);
            if (t.isShowTitle()) {
                continue;
            }
            if (!title.equals(t.getFirstLetter())) {
                T titleBean = (T) factory.create();
                titleBean.setShowTitle(true);
                titleBean.setFirstLetter(t.getFirstLetter());
                list.add(i, titleBean);
                title = t.getFirstLetter();
            }
        }
        factory.finish(list);
    }

    public static abstract class PinyinFactory<T> {
        public abstract T create();

        public abstract void finish(List<T> t);
    }
}
